/*
 * Copyright 2007 Gergely Kis
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.gwthtml.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class CSSParser {

	private static Map<String, String> parseStyleString(String str) {
		Map<String, String> ret = new HashMap<String, String>();
		if (str != null) {
			String[] propArray = str.split(";");
			for (String p : propArray) {
				String[] propComponents = p.split(":");
				if (propComponents.length != 2)
				{
					// Bad thing
					ret.clear();
					return ret;
				}
				ret.put(propComponents[0].trim(), propComponents[1].trim());
			}
		}
		return ret;
	}
	
	private static String serializeStyleMap(Map<String, String> styleMap) {
		Iterator<Entry<String,String>> iter = styleMap.entrySet().iterator();
		StringBuffer sb = new StringBuffer();
		while (iter.hasNext())
		{
			Entry<String, String> e = iter.next();
			sb.append(e.getKey());
			sb.append(":");
			sb.append(e.getValue());
			if (iter.hasNext()) {
				sb.append("; ");
			}
		}
		return sb.toString();
	}
	
	
	public static String getStyleAttribute(String input, String attr) {
		Map<String, String> styleMap = parseStyleString(input);
		return styleMap.get(attr);
	}
	
	public static String setStyleAttribute(String input, String attr, String value) {
		Map<String, String> styleMap = parseStyleString(input);
		if (value != null) 
		{
		 	styleMap.put(attr, value);
		} else {
			styleMap.remove(attr);
		}
		return serializeStyleMap(styleMap);
	}
}
